package com.itheima.reggie.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.UserHolder;
import com.itheima.reggie.domain.Address;
import com.itheima.reggie.mapper.AddressMapper;
import com.itheima.reggie.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;
    //保存
    @Override
    public void save(Address address) {

        //补齐参数
        address.setUserId(UserHolder.get().getId());
        address.setIsDefault(0); //0非默认地址


        addressMapper.insert(address);

    }

    //查询列表
    @Override
    public List<Address> findList() {

        //构造查询条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId()
        );
        return addressMapper.selectList(wrapper);
    }


    //按照id查询
    @Override
    public Address findById(Long id) {
        return addressMapper.selectById(id);
    }


    //修改
    @Override
    public void updateById(Address address) {
        addressMapper.updateById(address);
    }


    //删除
    @Override
    public void delete(List<Long> ids) {
        if (CollectionUtil.isNotEmpty(ids)) {
            addressMapper.deleteBatchIds(ids);

        }
    }


    @Override
    public void setDefault(Long id) {

        //现将当前用户下的地址全部设置为非默认的
        //设置更新内容
        Address address = new Address();
        address.setIsDefault(0);

        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId());
        addressMapper.update(address, wrapper);

        //将指定id的地址设置为默认
        Address address1 = new Address();
        address1.setIsDefault(1);
        address1.setId(id);
        addressMapper.updateById(address1);
    }


    //查询默认地址
    @Override
    public Address findDefault() {
        //构造查询条件
        LambdaQueryWrapper<Address> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Address::getUserId, UserHolder.get().getId())
                .eq(Address::getIsDefault, 1);
        return addressMapper.selectOne(wrapper);
    }

}
